// 共享数据

import {getTabledata,delTabledata, AddUser,EditUser} from './service'
import { message } from 'antd';
  const UserModel = {
    namespace: 'users', //命名空间
  
    state: { //存放数据的
      name: '',
      list:null,
      userlist:[]
    },


      //   同步
  reducers: {
    // 操作state 中的数据
    getlist(state, action) {
      console.log(state,'state');
      console.log(action,'action');

      return { ...state, ...action.payload };  //返回数据

    },
    // 启用 immer 之后
    // save(state, action) {
    //   state.name = action.payload;
    // },
  },
  
  
  //   异步
    effects: {
      *GetUserlist({ payload }, { call, put }) {
          const data = yield call(getTabledata);
          console.log(data);
          
          yield put({
              type:'getlist',
              payload: {data}, //返回后台的数据

          })
      },
      *DelUserlist({ payload:{ids} }, { call, put }) {
        const data = yield call(delTabledata,{ids});
        if (data) {
          message.success('删除成功')
          yield put({
            type:'GetUserlist',
            payload: {},

        })
        } else {
          message.error('删除失败');
        }        

    },

    // 在index里使用回调函数callback,用法如下，根据后端接口来判断窗口的开关
    *AddUserlist({ payload,callback}, { call, put }) {
      const response = yield call(AddUser,payload);
      if (response) {
        message.success('修改成功')
      if (callback) {callback(response)}  
      yield put({
        type:'GetUserlist',
        payload: {},
      })
      } else {
        message.error('修改失败');  
      }        
    },
  *EditUserlist({ payload:{values},callback }, { call, put }) {
    const data = yield call(EditUser,{...values});
    if (data) {
      message.success('修改成功')
      if (callback) {callback(response)}  
      yield put({
        type:'GetUserlist',
        payload: {},

    })
    } else {
      message.error('修改失败');

    }        
},
 
  },
    subscriptions: {    //订阅  （晒博思奎婆醒）
      setup({ dispatch, history }) {
        return history.listen(({ pathname }) => {
          if (pathname === '/users') {
            dispatch({
              type: 'GetUserlist',
            });
          }
        });
      },
    },
  };
  
  export default UserModel; //导出处model